package com.study.samsung.Utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 通用的工具类
 */
public class CommonUtils {
    /**根据名字获取Cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cs = request.getCookies();
        if(cs!=null) {
            for (Cookie c : cs) {
                if(c!=null && c.getName().equals(name)) {
                    return c;
                }
            }
        }
        return null;
    }
    /**
     * 将Map中的查询条件，加上前缀，以&拼接
     * @param map
     * @return  search_keyword=你好&id=3& 返回格式参考
     */
    public static  String generateParamterForSearch(Map<String,String> map){
        if(null == map || map.isEmpty()){
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Iterator<Map.Entry<String,String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String,String> entry = entries.next();
            if(!"".equals(entry.getValue())) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
        }
        return sb.toString();//如果带参数，最后携带了&符号
    }

    /**根据参数前缀，获取所有参数并存储到Map集合中
     * @param request
     * @param prefix
     */
    public static Map<String,String> getParametersStartingWith(HttpServletRequest request, String prefix) {
        Enumeration<String> enu = request.getParameterNames();
        Map<String, String> map = new TreeMap<String, String>();
        while(enu!=null && enu.hasMoreElements()) {
            String name = enu.nextElement();
            if(name.startsWith(prefix)) {
                map.put(name, request.getParameter(name));
            }
        }
        return map;
    }
}
